package org.edu.modules.act.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.activiti.core.common.spring.security.policies.ActivitiForbiddenException;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.history.*;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.edu.modules.act.common.result.PaginationBuilder;
import org.edu.modules.act.entity.*;
import org.edu.modules.act.mapper.*;
import org.edu.modules.act.service.WordOnlineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 流程任务历史信息的业务逻辑实现层
 *
 * @版权所有 福州土著人信息科技有限公司
 */
@Service
@Transactional
public class HistoryServiceImpl implements org.edu.modules.act.service.HistoryService {

	private static final String PROCESSINSTANCEID = "processInstanceId";

	@Autowired
	private HistoryService historyService;

	@Autowired
	private RepositoryService repositoryService;

	@Autowired
	private org.activiti.engine.TaskService taskService;

	@Resource
	private ActReModelMapper actReModelMapper;
	@Resource
	private ActRuInstanceFileMapper actRuInstanceFileMapper;
	@Resource
	private IVeBaseTeacherMapper iVeBaseTeacherMapper;
	@Resource
	private VeBaseDepartmentMapper veBaseDepartmentMapper;
	@Resource
	private ActReWordModelMapper actReWordModelMapper;

	@Autowired
	private WordOnlineService wordOnlineService;
	/**
	 * 查询流程实例历史数据分页
	 */
	@SuppressWarnings("all")
	@Override
	public Map<String, Object> queryHistoricProcessInstance(Integer currentPage, Integer pageSize, String processInstanceName, String processDefinitionName,
			String username) {
		System.out.println(username+"用户ID");

		HistoricProcessInstanceQuery historicProcessInstanceQuery = historyService.createHistoricProcessInstanceQuery();
		if (StringUtils.isNotBlank(processInstanceName)) {
			historicProcessInstanceQuery.processInstanceNameLike("%" + processInstanceName + "%");
		}
		if (StringUtils.isNotBlank(processDefinitionName)) {
			historicProcessInstanceQuery.processDefinitionName(processDefinitionName);
		}
		if (StringUtils.isNotBlank(username)) {
			historicProcessInstanceQuery.startedBy(username);
		}
		List<HistoricProcessInstance> historicProcessInstanceList = historicProcessInstanceQuery.orderByProcessInstanceStartTime().desc()
				.listPage(pageSize * (currentPage - 1), pageSize);
		List<LinkedHashMap<String, Object>> resultList = new ArrayList<>();
		for (int i = 0; i < historicProcessInstanceList.size(); i++) {
			LinkedHashMap<String, Object> historicProcessInstanceMap = new LinkedHashMap<>();
			historicProcessInstanceMap.put("id", historicProcessInstanceList.get(i).getId());
			historicProcessInstanceMap.put(PROCESSINSTANCEID, historicProcessInstanceList.get(i).getId());
			historicProcessInstanceMap.put("businessKey", historicProcessInstanceList.get(i).getBusinessKey());
			historicProcessInstanceMap.put("deleteReason", historicProcessInstanceList.get(i).getDeleteReason());
			historicProcessInstanceMap.put("deploymentId", historicProcessInstanceList.get(i).getDeploymentId());
			historicProcessInstanceMap.put("description", historicProcessInstanceList.get(i).getDescription());
			historicProcessInstanceMap.put("durationInMillis", historicProcessInstanceList.get(i).getDurationInMillis());
			historicProcessInstanceMap.put("endActivityId", historicProcessInstanceList.get(i).getEndActivityId());
			historicProcessInstanceMap.put("endTime", historicProcessInstanceList.get(i).getEndTime());
			historicProcessInstanceMap.put("name", historicProcessInstanceList.get(i).getName());
			historicProcessInstanceMap.put("processDefinitionId", historicProcessInstanceList.get(i).getProcessDefinitionId());
			historicProcessInstanceMap.put("processDefinitionKey", historicProcessInstanceList.get(i).getProcessDefinitionKey());
			historicProcessInstanceMap.put("processDefinitionName", historicProcessInstanceList.get(i).getProcessDefinitionName());
			historicProcessInstanceMap.put("processDefinitionVersion", historicProcessInstanceList.get(i).getProcessDefinitionVersion());
			historicProcessInstanceMap.put("processVariables", historicProcessInstanceList.get(i).getProcessVariables());
			historicProcessInstanceMap.put("startActivityId", historicProcessInstanceList.get(i).getStartActivityId());
			historicProcessInstanceMap.put("startTime", historicProcessInstanceList.get(i).getStartTime());
			historicProcessInstanceMap.put("startUserId", historicProcessInstanceList.get(i).getStartUserId());
			historicProcessInstanceMap.put("superProcessInstanceId", historicProcessInstanceList.get(i).getSuperProcessInstanceId());
			historicProcessInstanceMap.put("tenantId", historicProcessInstanceList.get(i).getTenantId());
			List<HistoricVariableInstance> historicVariableInstanceList = historyService.createHistoricVariableInstanceQuery()
					.processInstanceId(historicProcessInstanceList.get(i).getId()).list();
			boolean approved = false;
			for (HistoricVariableInstance historicVariableInstance : historicVariableInstanceList) {
				if ("approved".equals(historicVariableInstance.getVariableName())) {
					approved = (boolean) historicVariableInstance.getValue();
				}
			}
			String processStatus = null;
			if (historicProcessInstanceList.get(i).getDeleteReason() != null && historicProcessInstanceList.get(i).getEndTime() != null) {
				processStatus = "已终止";
			} else if (approved == true && historicProcessInstanceList.get(i).getDeleteReason() == null
					&& historicProcessInstanceList.get(i).getEndTime() != null) {
				processStatus = "审批通过";
			} else if (approved == false && historicProcessInstanceList.get(i).getDeleteReason() == null
					&& historicProcessInstanceList.get(i).getEndTime() != null) {
				processStatus = "已驳回";
			} else if (historicProcessInstanceList.get(i).getEndTime() == null) {
				processStatus = "审批中";
			}
			historicProcessInstanceMap.put("processStatus", processStatus);
			List<Comment> commentList = taskService.getProcessInstanceComments(historicProcessInstanceList.get(i).getId());// 查询该流程实例ID的所有批注 NOSONAR
			List<String> comments = new ArrayList<>();
			for (int j = 0; j < commentList.size(); j++) {
				SimpleDateFormat sdf =   new SimpleDateFormat( " yyyy-MM-dd HH:mm:ss " );
				String str = sdf.format(commentList.get(j).getTime());
				QueryWrapper<VeBaseTeacherEntity> wrapper3=new QueryWrapper<>();
				wrapper3.eq("userId", commentList.get(j).getUserId());
				List<VeBaseTeacherEntity> list3 = iVeBaseTeacherMapper.selectList(wrapper3);
				comments.add(list3.get(0).getXM() + "," + commentList.get(j).getFullMessage() +","+str+ ","+commentList.get(j).getUserId());
			}

			//获取部署ID
			String deploymentId =historicProcessInstanceList.get(i).getDeploymentId();
			//根据部署ID去查找模型
			QueryWrapper<ActReModelEntity> wrapper=new QueryWrapper<>();
			wrapper.eq("DEPLOYMENT_ID_",deploymentId);
			List<ActReModelEntity> list = actReModelMapper.selectList(wrapper);
			if(list== null || list.size()<1){
				System.out.println("DEPLOYMENT_ID_ = "+deploymentId + " 没有找到 act_re_model");
				continue;
			}
			historicProcessInstanceMap.put("modelInfo",list.get(0));
			historicProcessInstanceMap.put("comments", comments);
			//获取该流程实例绑定的文件表数据获取url和表单
			QueryWrapper<ActRuInstanceFileEntity> wrapper1 = new QueryWrapper<>();
			wrapper1.eq("PROC_INST_ID", historicProcessInstanceList.get(i).getId());
			List<ActRuInstanceFileEntity> list1 = actRuInstanceFileMapper.selectList(wrapper1);
			//String modelId="";
			if(list1!=null && list1.size()>0) {
				//根据ModelId去查找模板的url
				String modelId = list.get(0).getId();

				QueryWrapper<ActReWordModel> wrapper5 = new QueryWrapper();
				wrapper5.eq("MODEL_ID", modelId);
				//获取该实例的word模板
				List<ActReWordModel> wordList = actReWordModelMapper.selectList(wrapper5);

				String h5 = list1.get(0).getWordFileUrl();

				String oldH5 = wordList.get(0).getWordH5();
//			System.out.println("新的h5:------------------------------");
//			System.out.println(h5);
//			System.out.println("旧的h5------------------------------");
//			System.out.println(oldH5);

				String[] split = oldH5.split("\\{\\{auditOpinion1\\}\\}");
				String save = split[0].substring(split[0].length() - 300);
//			System.out.println("save------------------------------");
//			System.out.println(save);
				String[] header = h5.split(save);
				String[] end = oldH5.split(save);
//			System.out.println("end.length =  "+end.length);
				String newH5 = header[0] + save + end[1];
//			System.out.println("newH5--------------------------");
//			System.out.println(newH5);

				//获取表单的h5的代码

				Map<String ,String > map= new LinkedHashMap<>();
				for (int j = comments.size()-1; j >=0 ; j--) {
					String[] arr = comments.get(j).split(",");
					map.put(arr[3],comments.get(j));
				}
				System.out.println("这是我的批注集合"+map);
				//替换标识符为回填消息
	//			for (int j = 0; j < map.size() ; j++) {
	//				String[] arr = map.get(j).split(",");
	//				newH5 = newH5.replace("{{auditOpinion"+(j+1)+"}}",arr[1]);
	//				newH5 = newH5.replace("{{auditName"+(j+1)+"}}",arr[0]);
	//				newH5 = newH5.replace("{{auditTime"+(j+1)+"}}",arr[2]);
	//			}
				Set<Map.Entry<String, String>> entries = map.entrySet();
				int mark=1;
				for(Map.Entry entry : entries ){
					String comm=entry.toString().split("=")[1];
					String[] arr=comm.split(",");
					newH5 = newH5.replace("{{auditOpinion"+mark+"}}",arr[1]);
					newH5 = newH5.replace("{{auditName"+mark+"}}",arr[0]);
					newH5 = newH5.replace("{{auditTime"+mark+"}}",arr[2]);
					mark++;
				}
				for (int j = map.size(); j < 10; j++) {
					newH5 = newH5.replace("{{auditOpinion"+j+"}}","");
					newH5 = newH5.replace("{{auditName"+j+"}}","");
					newH5 = newH5.replace("{{auditTime"+j+"}}","");
				}
				list1.get(0).setWordFileUrl(newH5);
				historicProcessInstanceMap.put("wordAndAccessUrl", list1.get(0));

				//查询我的任务时，获取用户信息（taecher表）
				QueryWrapper<VeBaseTeacherEntity> wrapper2 = new QueryWrapper<>();
				wrapper2.eq("userId",historicProcessInstanceList.get(i).getStartUserId());
				List<VeBaseTeacherEntity> list2 = iVeBaseTeacherMapper.selectList(wrapper2);
				historicProcessInstanceMap.put("userInfo", list2.get(0));

				//获取该用户的部门信息
				QueryWrapper<VeBaseDepartment> wrapper4 = new QueryWrapper<>();
				wrapper4.eq("id",list2.get(0).getDepId());
				List<VeBaseDepartment> list4 = veBaseDepartmentMapper.selectList(wrapper4);
				historicProcessInstanceMap.put("userDepartment", list4.get(0));
			}else{
				System.out.println("PROC_INST_ID="+historicProcessInstanceList.get(i).getId() + "  没有找到 act_ru_instance_file");
			}

			resultList.add(historicProcessInstanceMap);
		}

//		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//		String roleData = sysRoleServiceClient.queryRoleData("historicprocessinstance", authentication.getName());
//		String[] roleDataArray = roleData == null ? null : roleData.split(",");
//		if (roleDataArray != null && roleDataArray.length > 0) {// 处理数据权限
//			return PaginationBuilder.buildResult(CollectionUtils.convertFilterList(resultList, roleDataArray), historicProcessInstanceQuery.count(),
//					currentPage, pageSize);
//		} else {
//			return PaginationBuilder.buildResult(resultList, historicProcessInstanceQuery.count(), currentPage, pageSize);
//		}
		return PaginationBuilder.buildResult(resultList, historicProcessInstanceQuery.count(), currentPage, pageSize);
	}

	/**
	 * 查询节点执行历史数据分页
	 */
	@Override
	public LinkedHashMap<String, Object> queryHistoricActivityInstance(Integer currentPage, Integer pageSize, String processInstanceId) {
		HistoricActivityInstanceQuery historicActivityInstanceQuery = historyService.createHistoricActivityInstanceQuery();
		if (StringUtils.isNotBlank(processInstanceId)) {
			historicActivityInstanceQuery.processInstanceId(processInstanceId);
		}
		List<HistoricActivityInstance> historicActivityInstanceList = historicActivityInstanceQuery.listPage(pageSize * (currentPage - 1), pageSize);
		LinkedHashMap<String, Object> resultMap = new LinkedHashMap<>();
		resultMap.put("list", historicActivityInstanceList);
		LinkedHashMap<String, Long> paginationMap = new LinkedHashMap<>();
		paginationMap.put("total", historicActivityInstanceQuery.count());
		paginationMap.put("pageSize", (long) pageSize);
		paginationMap.put("current", (long) currentPage);
		resultMap.put("pagination", paginationMap);
		return resultMap;
	}

	/**
	 * 查询流程实例和节点执行的详细信息历史数据分页
	 */
	@Override
	public LinkedHashMap<String, Object> queryHistoricDetail(Integer currentPage, Integer pageSize, String processInstanceId) {
		HistoricDetailQuery historicDetailQuery = historyService.createHistoricDetailQuery();
		if (StringUtils.isNotBlank(processInstanceId)) {
			historicDetailQuery.processInstanceId(processInstanceId);
		}
		List<HistoricDetail> historicDetailList = historicDetailQuery.orderByTime().desc().listPage(pageSize * (currentPage - 1), pageSize);
		LinkedHashMap<String, Object> resultMap = new LinkedHashMap<>();
		resultMap.put("list", historicDetailList);
		LinkedHashMap<String, Long> paginationMap = new LinkedHashMap<>();
		paginationMap.put("total", historicDetailQuery.count());
		paginationMap.put("pageSize", (long) pageSize);
		paginationMap.put("current", (long) currentPage);
		resultMap.put("pagination", paginationMap);
		return resultMap;
	}

	/**
	 * 查询流程实例已结束的变量历史数据分页
	 */
	@Override
	public Map<String, Object> queryHistoricVariableInstance(Integer currentPage, Integer pageSize, String processInstanceId) throws ParseException {
		HistoricVariableInstanceQuery historicVariableInstanceQuery = historyService.createHistoricVariableInstanceQuery();
		if (StringUtils.isNotBlank(processInstanceId)) {
			historicVariableInstanceQuery.processInstanceId(processInstanceId);
		}
		List<HistoricVariableInstance> historicVariableInstanceList = historicVariableInstanceQuery.listPage(pageSize * (currentPage - 1), pageSize);
		List<LinkedHashMap<String, Object>> resultList = new ArrayList<>();
		for (int i = 0; i < historicVariableInstanceList.size(); i++) {
			LinkedHashMap<String, Object> variableInstanceMap = new LinkedHashMap<>();
			variableInstanceMap.put("id", historicVariableInstanceList.get(i).getId());
			variableInstanceMap.put("variableName", historicVariableInstanceList.get(i).getVariableName());
			variableInstanceMap.put("variableTypeName", historicVariableInstanceList.get(i).getVariableTypeName());
			if ("date".equals(historicVariableInstanceList.get(i).getVariableTypeName())) {
				SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
				Date date = simpleDateFormat.parse(historicVariableInstanceList.get(i).getValue().toString());
				simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				variableInstanceMap.put("value", simpleDateFormat.format(date));
			} else {
				variableInstanceMap.put("value", historicVariableInstanceList.get(i).getValue());
			}
			variableInstanceMap.put(PROCESSINSTANCEID, historicVariableInstanceList.get(i).getProcessInstanceId());
			variableInstanceMap.put("createTime", historicVariableInstanceList.get(i).getCreateTime());
			variableInstanceMap.put("lastUpdatedTime", historicVariableInstanceList.get(i).getLastUpdatedTime());
			variableInstanceMap.put("taskId", historicVariableInstanceList.get(i).getTaskId());
			variableInstanceMap.put("time", historicVariableInstanceList.get(i).getTime());
			resultList.add(variableInstanceMap);
		}

//		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//		String roleData = sysRoleServiceClient.queryRoleData("historicvariableinstance", authentication.getName());
//		String[] roleDataArray = roleData == null ? null : roleData.split(",");
//		if (roleDataArray != null && roleDataArray.length > 0) {// 处理数据权限
//			return PaginationBuilder.buildResult(CollectionUtils.convertFilterList(resultList, roleDataArray), historicVariableInstanceQuery.count(),
//					currentPage, pageSize);
//		} else {
//			return PaginationBuilder.buildResult(resultList, historicVariableInstanceQuery.count(), currentPage, pageSize);
//		}
		return PaginationBuilder.buildResult(resultList, historicVariableInstanceQuery.count(), currentPage, pageSize);
	}

	/**
	 * 查询流程任务历史数据分页
	 */
	@Override
	public Map<String, Object> queryHistoricTaskInstance(Integer currentPage, Integer pageSize, String taskName) {
		HistoricTaskInstanceQuery historicTaskInstanceQuery = historyService.createHistoricTaskInstanceQuery();
		if (StringUtils.isNotBlank(taskName)) {
			historicTaskInstanceQuery.taskNameLike("%" + taskName + "%");
		}
		List<HistoricTaskInstance> historicTaskInstanceList = historicTaskInstanceQuery.orderByHistoricTaskInstanceEndTime().desc()
				.listPage(pageSize * (currentPage - 1), pageSize);
		List<LinkedHashMap<String, Object>> resultList = new ArrayList<>();
		for (int i = 0; i < historicTaskInstanceList.size(); i++) {
			LinkedHashMap<String, Object> taskInstanceMap = new LinkedHashMap<>();
			taskInstanceMap.put("id", historicTaskInstanceList.get(i).getId());
			taskInstanceMap.put("assignee", historicTaskInstanceList.get(i).getAssignee());
			taskInstanceMap.put("category", historicTaskInstanceList.get(i).getCategory());
			taskInstanceMap.put("claimTime", historicTaskInstanceList.get(i).getClaimTime());
			taskInstanceMap.put("createTime", historicTaskInstanceList.get(i).getCreateTime());
			taskInstanceMap.put("deleteReason", historicTaskInstanceList.get(i).getDeleteReason());
			taskInstanceMap.put("description", historicTaskInstanceList.get(i).getDescription());
			taskInstanceMap.put("dueDate", historicTaskInstanceList.get(i).getDueDate());
			taskInstanceMap.put("durationInMillis", historicTaskInstanceList.get(i).getDurationInMillis());
			taskInstanceMap.put("endTime", historicTaskInstanceList.get(i).getEndTime());
			taskInstanceMap.put("executionId", historicTaskInstanceList.get(i).getExecutionId());
			taskInstanceMap.put("formKey", historicTaskInstanceList.get(i).getFormKey());
			taskInstanceMap.put("name", historicTaskInstanceList.get(i).getName());
			taskInstanceMap.put("owner", historicTaskInstanceList.get(i).getOwner());
			taskInstanceMap.put("parentTaskId", historicTaskInstanceList.get(i).getParentTaskId());
			taskInstanceMap.put("priority", historicTaskInstanceList.get(i).getPriority());
			taskInstanceMap.put("processDefinitionId", historicTaskInstanceList.get(i).getProcessDefinitionId());
			taskInstanceMap.put(PROCESSINSTANCEID, historicTaskInstanceList.get(i).getProcessInstanceId());
			taskInstanceMap.put("processVariables", historicTaskInstanceList.get(i).getProcessVariables());
			taskInstanceMap.put("startTime", historicTaskInstanceList.get(i).getStartTime());
			taskInstanceMap.put("taskDefinitionKey", historicTaskInstanceList.get(i).getTaskDefinitionKey());
			taskInstanceMap.put("taskLocalVariables", historicTaskInstanceList.get(i).getTaskLocalVariables());
			taskInstanceMap.put("tenantId", historicTaskInstanceList.get(i).getTenantId());
			taskInstanceMap.put("time", historicTaskInstanceList.get(i).getTime());
			taskInstanceMap.put("workTimeInMillis", historicTaskInstanceList.get(i).getWorkTimeInMillis());
			taskInstanceMap.put("status", historicTaskInstanceList.get(i).getEndTime() == null ? "办理中" : "已结束");
			ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) repositoryService
					.getProcessDefinition(historicTaskInstanceList.get(i).getProcessDefinitionId());
			taskInstanceMap.put("processDefinitionName", processDefinition.getName());
			List<Comment> commentList = taskService.getProcessInstanceComments(historicTaskInstanceList.get(i).getProcessInstanceId());// 查询该流程实例ID的所有批注 NOSONAR
			List<String> comments = new ArrayList<>();
			for (int j = 0; j < commentList.size(); j++) {
				comments.add(commentList.get(j).getUserId() + "：" + commentList.get(j).getFullMessage() + "\n");
			}
			taskInstanceMap.put("comments", comments);
			resultList.add(taskInstanceMap);
		}

//		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//		String roleData = sysRoleServiceClient.queryRoleData("historictaskinstance", authentication.getName());
//		String[] roleDataArray = roleData == null ? null : roleData.split(",");
//		if (roleDataArray != null && roleDataArray.length > 0) {// 处理数据权限
//			return PaginationBuilder.buildResult(CollectionUtils.convertFilterList(resultList, roleDataArray), historicTaskInstanceQuery.count(), currentPage,
//					pageSize);
//		} else {
//			return PaginationBuilder.buildResult(resultList, historicTaskInstanceQuery.count(), currentPage, pageSize);
//		}
		return PaginationBuilder.buildResult(resultList, historicTaskInstanceQuery.count(), currentPage, pageSize);
	}

	/**
	 * 删除流程实例历史数据
	 */
	@Override
	public void deleteHistoricProcessInstance(String processInstanceId) {
		Task task = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();
		if (task != null) {
			throw new ActivitiForbiddenException("包含流程实例中的任务，不能删除");
		}
		historyService.deleteHistoricProcessInstance(processInstanceId);
	}

	/**
	 * 删除流程任务历史数据
	 */
	@Override
	public void deleteHistoricTaskInstance(String id) {
		historyService.deleteHistoricTaskInstance(id);
	}

}
